import React, { useState, useEffect } from 'react';
import { Layout, Card, Select, DatePicker, Row, Col, Statistic, Spin, message, Button, Space } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, ReloadOutlined, ArrowLeftOutlined, CalendarOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import { dataService } from '../../services/dataService';
import type { ChartListItem, ChartDataParams, ChartDataResponse, SummaryDataResponse } from '../../services/dataService';
import dayjs from 'dayjs';
import './DataOverviewPage.css';
import { useNavigate } from 'react-router-dom';

const { Content } = Layout;
const { RangePicker } = DatePicker;
const { Option } = Select;

type TimeRangeType = 'recent7' | 'recent30' | 'custom';

export const DataOverviewPage: React.FC = () => {
    const navigate = useNavigate();

    // 状态管理
    const [chartList, setChartList] = useState<ChartListItem[]>([]);
    const [selectedChart, setSelectedChart] = useState<string>('');
    const [timeRange, setTimeRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
    const [timeRangeType, setTimeRangeType] = useState<TimeRangeType>('recent7');
    const [loading, setLoading] = useState(false);
    const [chartData, setChartData] = useState<ChartDataResponse | null>(null);
    const [summaryData, setSummaryData] = useState<SummaryDataResponse['summary'] | null>(null);
    const [chartInstance, setChartInstance] = useState<echarts.ECharts | null>(null);

    // 初始化图表
    const initChart = () => {
        const chartDom = document.getElementById('data-overview-chart');
        if (!chartDom) {
            console.error('图表容器不存在');
            return null;
        }

        try {
            const chart = echarts.init(chartDom);
            console.log('图表初始化成功');
            return chart;
        } catch (error) {
            console.error('图表初始化失败:', error);
            return null;
        }
    };

    // 更新图表
    const updateChart = (chart: echarts.ECharts, data: ChartDataResponse) => {
        if (!chart || !data) return;

        const option = {
            title: {
                text: data.title,
                subtext: data.subtitle,
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: (params: any) => {
                    const item = params[0];
                    const unit = data.meta[data.yField]?.unit || '';
                    return `${item.name}<br/>${item.seriesName}: ${item.value}${unit}`;
                }
            },
            legend: {
                data: [data.meta[data.yField]?.alias || data.yField],
                bottom: 10
            },
            grid: {
                left: '60px',
                right: '40px',
                bottom: '60px',
                top: '80px'
            },
            xAxis: {
                type: 'category',
                data: data.data.map(item => item[data.xField])
            },
            yAxis: {
                type: 'value',
                name: data.meta[data.yField]?.alias || data.yField
            },
            series: [{
                name: data.meta[data.yField]?.alias || data.yField,
                type: 'line',
                smooth: true,
                areaStyle: { opacity: 0.3 },
                data: data.data.map(item => Number(item[data.yField]) || 0)
            }]
        };

        try {
            chart.setOption(option);
            chart.resize();
            console.log('图表更新成功');
        } catch (error) {
            console.error('图表更新失败:', error);
        }
    };

    // 获取数据
    const loadData = async () => {
        if (!selectedChart || !timeRange) return;

        setLoading(true);
        try {
            const params: ChartDataParams = {
                store: 1,
                chartId: selectedChart,
                timeRangeStart: timeRange[0].format('YYYY-MM-DD'),
                timeRangeEnd: timeRange[1].format('YYYY-MM-DD'),
                limit: 100
            };

            const [chartResponse, summaryResponse] = await Promise.all([
                dataService.getChartData(params),
                dataService.getSummaryData(params)
            ]);

            if (chartResponse.code === 0 && chartResponse.data) {
                setChartData(chartResponse.data);

                // 获取或创建图表实例
                let chart = chartInstance;
                if (!chart) {
                    chart = initChart();
                    if (chart) {
                        setChartInstance(chart);
                    }
                }

                // 更新图表
                if (chart && chartResponse.data) {
                    updateChart(chart, chartResponse.data);
                }
            }

            if (summaryResponse.code === 0 && summaryResponse.data) {
                setSummaryData(summaryResponse.data.summary);
            }
        } catch (error) {
            message.error('获取数据失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取图表列表
    const loadChartList = async () => {
        try {
            const response = await dataService.getChartList();
            if (response.code === 0 && response.data) {
                setChartList(response.data);
                if (response.data.length > 0) {
                    setSelectedChart(response.data[0].id);
                }
            }
        } catch (error) {
            message.error('获取图表列表失败');
        }
    };

    // 处理时间范围切换
    const handleTimeRangeChange = (type: TimeRangeType) => {
        setTimeRangeType(type);

        if (type === 'recent7') {
            setTimeRange([dayjs().subtract(6, 'day'), dayjs()]);
        } else if (type === 'recent30') {
            setTimeRange([dayjs().subtract(1, 'month'), dayjs()]);
        }
    };

    // 处理自定义时间范围
    const handleCustomTimeChange = (dates: [dayjs.Dayjs, dayjs.Dayjs] | null) => {
        setTimeRange(dates);
        if (dates) {
            setTimeRangeType('custom');
        }
    };

    // 获取时间范围显示文本
    const getTimeRangeText = () => {
        if (!timeRange) return '';

        if (timeRangeType === 'recent7') return '最近7天';
        if (timeRangeType === 'recent30') return '最近30天';

        return `${timeRange[0].format('MM-DD')} 至 ${timeRange[1].format('MM-DD')}`;
    };

    // 组件初始化
    useEffect(() => {
        loadChartList();
        handleTimeRangeChange('recent7'); // 设置默认时间范围
    }, []);

    // 当图表或时间范围变化时加载数据
    useEffect(() => {
        if (selectedChart && timeRange) {
            loadData();
        }
    }, [selectedChart, timeRange]);

    // 组件卸载时清理图表
    useEffect(() => {
        return () => {
            if (chartInstance) {
                try {
                    chartInstance.dispose();
                } catch (error) {
                    console.log('清理图表实例失败:', error);
                }
            }
        };
    }, [chartInstance]);

    return (
        <Layout className="data-overview-layout">
            <div className="orders-header">
                <div className="header-left">
                    <Button
                        type="text"
                        icon={<ArrowLeftOutlined />}
                        size="large"
                        onClick={() => navigate('/dashboard')}
                    />
                    <h1 className="page-title">数据概览</h1>
                </div>
            </div>

            <Content className="data-overview-content">
                <div className="data-overview-container">
                    <div className="data-overview-header">
                        <div className="data-overview-title">
                            <h1>数据概览</h1>
                            {timeRange && (
                                <div className="time-range-indicator">
                                    <CalendarOutlined style={{ marginRight: 4 }} />
                                    <span>{getTimeRangeText()}</span>
                                </div>
                            )}
                        </div>

                        <div className="data-overview-controls">
                            <div className="controls-row">
                                <div className="controls-left">
                                    <Select
                                        placeholder="选择图表"
                                        value={selectedChart}
                                        onChange={setSelectedChart}
                                        style={{ width: 180 }}
                                    >
                                        {chartList.map(chart => (
                                            <Option key={chart.id} value={chart.id}>
                                                {chart.title}
                                            </Option>
                                        ))}
                                    </Select>

                                    <Space.Compact className="time-range-buttons">
                                        <Button
                                            type={timeRangeType === 'recent7' ? 'primary' : 'default'}
                                            onClick={() => handleTimeRangeChange('recent7')}
                                            size="small"
                                        >
                                            最近7天
                                        </Button>
                                        <Button
                                            type={timeRangeType === 'recent30' ? 'primary' : 'default'}
                                            onClick={() => handleTimeRangeChange('recent30')}
                                            size="small"
                                        >
                                            最近30天
                                        </Button>
                                        <Button
                                            type={timeRangeType === 'custom' ? 'primary' : 'default'}
                                            onClick={() => handleTimeRangeChange('custom')}
                                            size="small"
                                        >
                                            自定义
                                        </Button>
                                    </Space.Compact>
                                </div>

                                <Button
                                    icon={<ReloadOutlined />}
                                    onClick={loadData}
                                    size="small"
                                >
                                    刷新
                                </Button>
                            </div>

                            {timeRangeType === 'custom' && (
                                <div className="custom-time-range">
                                    <RangePicker
                                        value={timeRange}
                                        onChange={(dates) => handleCustomTimeChange(dates as [dayjs.Dayjs, dayjs.Dayjs] | null)}
                                        placeholder={['开始日期', '结束日期']}
                                        size="small"
                                        style={{ width: '100%', maxWidth: 300 }}
                                    />
                                </div>
                            )}
                        </div>
                    </div>

                    {loading ? (
                        <div className="data-overview-loading">
                            <Spin size="large" />
                        </div>
                    ) : (
                        <>
                            {summaryData && (
                                <Row gutter={16} className="data-overview-summary">
                                    <Col span={8}>
                                        <Card>
                                            <Statistic
                                                title={summaryData.meta.gmv?.alias || 'GMV'}
                                                value={summaryData.gmv || 0}
                                                suffix={summaryData.unit}
                                                valueStyle={{ color: '#3f8600' }}
                                            />
                                        </Card>
                                    </Col>
                                    <Col span={8}>
                                        <Card>
                                            <Statistic
                                                title={summaryData.meta.rate?.alias || '环比'}
                                                value={summaryData.rate}
                                                precision={2}
                                                valueStyle={{ color: summaryData.rate > 0 ? '#3f8600' : '#cf1322' }}
                                                prefix={summaryData.rate > 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                                                suffix={summaryData.meta.rate?.unit || '%'}
                                            />
                                        </Card>
                                    </Col>
                                    <Col span={8}>
                                        <Card>
                                            <Statistic
                                                title={summaryData.meta.same_rate?.alias || '同比'}
                                                value={summaryData.same_rate}
                                                precision={2}
                                                valueStyle={{ color: summaryData.same_rate > 0 ? '#3f8600' : '#cf1322' }}
                                                prefix={summaryData.same_rate > 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                                                suffix={summaryData.meta.same_rate?.unit || '%'}
                                            />
                                        </Card>
                                    </Col>
                                </Row>
                            )}

                            <Card className="data-overview-chart">
                                <div
                                    id="data-overview-chart"
                                    style={{ width: '100%', height: '400px' }}
                                />
                            </Card>
                        </>
                    )}
                </div>
            </Content>
        </Layout>
    );
};

export default DataOverviewPage; 